﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace Portal
{
    /// <summary>
    /// 文件上传帮助
    /// </summary>
    public class UploadHelper
    {
        public UploadHelper(HttpPostedFileBase postedFile, string relativePath)
        {
            PostedFile = postedFile;
            RelativePath = relativePath;
        }
        public UploadHelper()
        {

        }

        public HttpPostedFileBase PostedFile { get; set; }
        public string OriginalFileName { get; set; }
        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; }
        public string RelativePath { get; set; }
        public string Extension { get; set; }
        public string FileRelativePath { get { return Path.Combine(RelativePath, FileName); } private set { _fileRelativePath = value; } }
        public string FilePhyPath { get { return Path.Combine(PhyPath, FileName); } private set { _filePhyPath = value; } }
        public string PhyPath { get; private set; }
        public string ErrorMessage { get; private set; }
        public long PicMaxLength { get; set; }
        public string Base64 { get; set; }
        public bool IsImage { get; set; }
        private string _fileRelativePath;
        private string _filePhyPath;
        public bool Save()
        {
            try
            {
                if (IsImage)
                {
                    if (!CheckImage()) return false;
                }
                Check.Argument.IsNotNull(PostedFile, "PostedFile");
                Check.Argument.IsNotNull(RelativePath, "RelativePath");
                OriginalFileName = Path.GetFileName(PostedFile.FileName);//获得文件名            
                Extension = Path.GetExtension(PostedFile.FileName);//获得文件扩展名  
                FileName = Guid.NewGuid() + Extension;//实际保存文件名   
                PhyPath = HttpContext.Current.Server.MapPath(RelativePath);
                if (!Directory.Exists(PhyPath))
                {
                    Directory.CreateDirectory(PhyPath);
                }
                PostedFile.SaveAs(FilePhyPath);
                return true;
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }

        }
        /// <summary>
        /// 保存文件扩展
        /// </summary>
        /// <param name="postedFile">提交数据</param>
        /// <param name="relativePath">路径("/.../.../")</param>
        /// <returns></returns>
        public bool Save(HttpPostedFileBase postedFile, string relativePath)
        {
            PostedFile = postedFile;
            RelativePath = relativePath;
            return Save();
        }
        public bool Delete()
        {
            try
            {
                var phyPath = HttpContext.Current.Server.MapPath(FileRelativePath);
                FileHelper.DeleteSub(phyPath);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool Delete(string fileRelativePath)
        {
            try
            {
                var phyPath = HttpContext.Current.Server.MapPath(FileRelativePath);
                FileHelper.DeleteSub(phyPath);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool Delete(string[] fileRelativePath)
        {
            try
            {
                var phyPath = fileRelativePath.Select(o => HttpContext.Current.Server.MapPath(o));
                FileHelper.DeleteSub(phyPath.ToArray());
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 替换文件
        /// </summary>
        /// <param name="postedFile">post数据</param>
        /// <param name="relativePath"> </param>
        /// <param name="fileRelativePath">相对路径</param>
        /// <returns></returns>
        public bool ReplaceFile(HttpPostedFileBase postedFile, string relativePath, string fileRelativePath)
        {
            try
            {
                FileRelativePath = HttpContext.Current.Server.MapPath(fileRelativePath);
     
                Delete(); 
                RelativePath = relativePath;
                PostedFile = postedFile;
                Save();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 保存文件 
        /// </summary>
        /// <param name="base64"> </param>
        /// <param name="filepath">相对路径</param>
        /// <returns>[0]文件相对保存路径,[1]路径，[2]文件名，[3]物理路径</returns>
        public bool SaveImage(string base64, string filepath)
        {
            if (base64 == null)
            {
                return false;
            }
            var phyPath = HttpContext.Current.Server.MapPath(filepath);
            var saveName = Guid.NewGuid().ToString();//实际保存文件名   
            try
            {
                saveName = Base64StringToImageSave(phyPath, saveName, base64);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// base64编码的文本转为图片
        /// </summary>
        /// <param name="filepath"> </param>
        /// <param name="txtFileName">保存的路径加文件名</param>
        /// <param name="inputStr">要转换的文本</param>
        private string Base64StringToImageSave(string filepath, string txtFileName, string inputStr)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(inputStr);
                var ms = new MemoryStream(arr);
                var bmp = new Bitmap(ms);
                bmp.Save(filepath + txtFileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Close();
                return txtFileName + ".jpg";
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        public bool CheckImage()
        {
            if (PostedFile != null)
            {
                string picext = (Path.GetExtension(PostedFile.FileName) ?? "").ToLower();
                if (picext == ".jpg" || picext == ".gif" || picext == ".bmp" || picext == ".png" || picext == ".jpeg")
                {
                }
                else
                {
                    ErrorMessage = "不是有效的图片格式";
                    return false;
                }
                if (PostedFile.ContentLength > PicMaxLength)
                {
                    var contentLength = PicMaxLength;
                    float result;
                    string lblUnit;
                    if (contentLength >= 1073741824)
                    {
                        result = contentLength / 1073741824.00F;
                        lblUnit = "GB";
                    }
                    else if (contentLength >= 1048576)
                    {
                        result = contentLength / 1048576.00F;
                        lblUnit = "MB";
                    }
                    else
                    {
                        result = contentLength / 1024.00F;
                        lblUnit = "KB";
                    }
                    ErrorMessage = "图像大小不能超过" + result + lblUnit + "!";
                    return false;
                }
            }
            return true;
        }
    }
}
